import { onMounted, ref, watch } from 'vue'
import { Status } from '@/http/types.d'

interface watchOption {
  field: string
  formState: Recordable<Object>
}

interface option {
  api: PromiseFn
  cascade?: watchOption
}

export function useOptions<T = any>({ api, cascade }: option) {
  const data = ref<T[]>()

  const getOptions = async (field?: any) => {
    try {
      const res = await api(field)
      if (res.status === Status.SUCCESS) {
        data.value = res.data
      } else {
        data.value = []
      }
    } catch (err) {}
  }

  onMounted(() => {
    !cascade && getOptions()
  })

  if (cascade) {
    const { field, formState } = cascade
    watch(
      () => formState[field],
      val => {
        getOptions({ [field]: val })
      },
      { immediate: true }
    )
  }
  return data
}